package com.shuang.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shuang.common.JsonUtils;
import com.shuang.pojo.DbGoods;
import com.shuang.pojo.DbOrder;
import com.shuang.pojo.DbOrderJsp;
import com.shuang.pojo.DbOrderRecord;
import com.shuang.pojo.DbReceiveInformation;
import com.shuang.pojo.DbUser;
import com.shuang.pojo.ExtendDbGoods;
import com.shuang.pojo.ShoppingPojo;
import com.shuang.pojo.TempDbOrder;
import com.shuang.redis.JedisClient;
import com.shuang.service.DbGoodsClassService;
import com.shuang.service.DbGoodsService;
import com.shuang.service.DbOrderRecordService;
import com.shuang.service.DbOrderService;
import com.shuang.service.DbReceiveInformationService;
import com.shuang.service.DbUserService;
import com.shuang.solr.SolrClientService;

@Controller
public class PageHanlder {
			
			@Resource(name="dbGoodsService")
			private DbGoodsService dbGoodsService;
			
			@Resource(name="dbGoodsClassService")
			private DbGoodsClassService dbGoodsClassService;
			
			@Resource(name="solrClientService")
			private SolrClientService solrClientService;
			@Resource(name="jedisClient")
			private JedisClient jedisClient;
			
			@Value("${REDIS_USER_SESSION_KEY}")
			private String REDIS_USER_SESSION_KEY ;
			
			@Resource(name="dbUserService")
			private DbUserService dbUserService;
			
			@Resource(name="dbReceiveInformationService")
			private DbReceiveInformationService dbReceiveInformationService;
			@Resource(name="dbOrderService")
			private DbOrderService dbOrderService;
			
			@Resource(name="dbOrderRecordService")
			private DbOrderRecordService dbOrderRecordService;
	/**
	   * 打开后台主页面
	   * @return
	   */
		@RequestMapping("/back")
		public String showIndex(String token,Model model){
			if(token==""||token==null){
				return "redirect:/back/login?status=403&data=请登录";
			}
			String jsonStr=jedisClient.get(REDIS_USER_SESSION_KEY+":"+token);
			if(jsonStr==""||jsonStr==null){//自定义session超时或者错误
				return "redirect:/back/login?status=403&data=请登录";
			}
			model.addAttribute("backUserInfo",JsonUtils.jsonToPojo(jsonStr, DbUser.class) );
			model.addAttribute("SESSION_KEY", token);
			return "backjsp/index";
		}
		/**
		   * 打开其它主页面
		   * @return
		   */
		@RequestMapping("/back/{pageName}")
		public String showOtherPage(@PathVariable String pageName,String status,String data,Model model){
			if(status!=null&&status!=""){
				model.addAttribute("status",status);
			}
			if(data!=null&&data!=""){
				try {
					model.addAttribute("data", new String(data.getBytes("iso8859-1"),"utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			return "backjsp/"+pageName;
		}
		/**
		   * 打开其它主页面
		   * @return
		   */
		@RequestMapping("/{frontOrback}/showmore")
		public String showMorePage(@PathVariable String frontOrback,@RequestParam(value="id" ,defaultValue="-1") Long gId,Model model ,HttpServletRequest request){
			if(gId==null||gId==-1){
				return "404";
			}
			Cookie[] cookies = request.getCookies();
			model.addAttribute("userInfo",getFrontUserInfoByToken(cookies));
			ExtendDbGoods goodsInfo=dbGoodsService.selectGoodsById(gId);
			model.addAttribute("goodsInfo", goodsInfo);
			return frontOrback+"jsp/showmore";
		}
		/**
		   * 打开前台主页面
		   * @return
		   */
		@RequestMapping("/front/index")
		public String showFrontMainPage(Model model,HttpServletRequest request){
			Cookie[] cookies = request.getCookies();
			model.addAttribute("userInfo",getFrontUserInfoByToken(cookies));
			model.addAttribute("newGoodsList", dbGoodsService.selectNewGoodsListByPage(1, 12));
			model.addAttribute("goodsList", dbGoodsService.selectGoodsListStatusIOK(1, 8));
			model.addAttribute("classTree", dbGoodsClassService.selcetAllClass());
			return "frontjsp/index";
		}
		/**
		 * 打开用户订单页面
		 * @param model
		 * @param request
		 * @return
		 */
		@RequestMapping("/front/record")
		public String showRecordPage(Model model,HttpServletRequest request){
			Cookie[] cookies = request.getCookies();
			DbUser dbUser = (DbUser)getFrontUserInfoByToken(cookies);
			if(dbUser==null){
				return "redirect:/front/shopping?msg=请先登录";
			}
			List<DbOrder> orderList=dbOrderService.selBasicOrderInfo(dbUser.getuId());
			// TODO 代码质量不够好查询了多次数据库，需要修改
			List<DbOrderJsp> orderListTemp=new ArrayList<DbOrderJsp>();
			DbOrderJsp dbOrderJsp=null;
			for(DbOrder order:orderList){
				dbOrderJsp=new DbOrderJsp();
				dbOrderJsp.setoId(order.getoId());
				dbOrderJsp.setoCreateTime(order.getoCreateTime());
				dbOrderJsp.setoAudit(order.getoAudit());
				dbOrderJsp.setoStatus(order.getoStatus());
				dbOrderJsp.setoTotalMonmy(order.getoTotalMonmy());
				List<DbOrderRecord> tempList=dbOrderRecordService.selRecordByOId(order.getoId());
				dbOrderJsp.setRecords(tempList);
				orderListTemp.add(dbOrderJsp);
			}
			
			model.addAttribute("orderList",orderListTemp);
			return "frontjsp/record";
		}
		
		/**
		   * 打开订单页面
		   * @return
		   */
		@RequestMapping("/front/order")
		public String showOrderPage(Model model,HttpServletRequest request,String id){
			
			Cookie[] cookies = request.getCookies();
			DbUser dbUser = (DbUser)getFrontUserInfoByToken(cookies);
			if(dbUser==null){
				return "redirect:/front/shopping?msg=请先登录";
			}
			
			List<DbReceiveInformation> receiveInformationList=dbReceiveInformationService.getReceiveInfomationByUid(dbUser.getuId());
			model.addAttribute("receiveInformationList", receiveInformationList);//地址信息
			
			DbReceiveInformation dbReceiveInformation=receiveInformationList.get(0);//默认地址信息为最新加入的地址
			
			List<ShoppingPojo> listSave=new ArrayList<ShoppingPojo>();//要保存到订单的商品信息
			
			Long o_monmy=0l;
			List<ShoppingPojo> list=getShoppingList(cookies);
			String[] strs = id.split(",");
			for(String st:strs){
				if(!st.equals("")){
					for(ShoppingPojo li:list){
						if(li.getgId()==Long.parseLong(st)){//是订单中的商品
							listSave.add(li);
							o_monmy+=li.getgPrice()*li.getS_number();
						}
					}
				}
			}
			TempDbOrder  tempOrder=dbOrderService.createTempOrder(dbUser.getuId(),dbReceiveInformation,o_monmy,listSave);
			model.addAttribute("tempOrder",tempOrder);
			model.addAttribute("goodsList",listSave);
			model.addAttribute("userInfo",dbUser);
			return "frontjsp/Order";
		}
		/**
		   * 打开前台页面
		   * @return
		   */
		@RequestMapping("/front/{pageName}")
		public String showFrontPage(@PathVariable String pageName,Model model,HttpServletRequest request){
			Cookie[] cookies = request.getCookies();
			model.addAttribute("userInfo",getFrontUserInfoByToken(cookies));
			return "frontjsp/"+pageName;
		}
		
		/**
		   * 打开购物车页面
		   * @return
		   */
		@RequestMapping("/front/shopping")
		public String showShoppingCart(Model model,HttpServletRequest request) {
			Cookie[] cookies = request.getCookies();
			/*if(getFrontUserInfoByToken(cookies)==null){
				return "redirect:/front/index";
			}*/
			List<ShoppingPojo> list=getShoppingList(cookies);
			model.addAttribute("shoppingList", list);
			model.addAttribute("userInfo",getFrontUserInfoByToken(cookies));
			return "frontjsp/shopping";
		}
		
		/**
		   * 打开注册登陆验证码
		   * @return
		   */
		@RequestMapping("/front/valiCodeImg/{type}")
		public String showValiCodeImg(@PathVariable String type,Model model){
			if(type.equals("register")){
				model.addAttribute("type", 1);
			}else if(type.equals("login")){
				model.addAttribute("type", 2);
			}
			return "frontjsp/valiCodeImg";
		}
		
		@RequestMapping(value="/front/search" ,method=RequestMethod.GET)
		public String searchGoods(String search,
				@RequestParam(value="page" ,defaultValue="1")Integer page,
				@RequestParam(value="rows" ,defaultValue="30")Integer rows,
				Model model,HttpServletRequest request) throws UnsupportedEncodingException{
			if(search==""||search==null){
				return "404";
			}
			Cookie[] cookies = request.getCookies();
			model.addAttribute("userInfo",getFrontUserInfoByToken(cookies));
			search=new String(search.getBytes("iso8859-1"),"utf-8");
			Map<String ,Object> result =solrClientService.searchGoods(page,rows,search);
			model.addAttribute("searchResult", result);
			return  "frontjsp/search";
		}
		@RequestMapping("/quit/{type}")
		@ResponseBody
		public Map<String ,Object> quit(HttpServletRequest request,@PathVariable String type){
			if(type==null||type==""){
				Map<String ,Object> result =new HashMap<String, Object>();
				result.put("status", 403);
				result.put("data", "操作类型不合法");
				return result;
			}
			Cookie[] cookies = request.getCookies();
			return dbUserService.quit(type,cookies);
		} 
		/**
		 * 前台用户信息获取
		 * @param cookies
		 * @return
		 */
		private Object getFrontUserInfoByToken(Cookie[] cookies){
			if(cookies!=null&&cookies.length>0){
				for(Cookie cookie:cookies){
					if(cookie.getName().equals("FRONT_SESSION_KEY")){
						String token=cookie.getValue();
						System.out.println(token);
						String userInfoString=jedisClient.get(REDIS_USER_SESSION_KEY+":"+token);//获取用户的信息
						if(userInfoString!=null&&userInfoString!=""){
							return JsonUtils.jsonToPojo(userInfoString,DbUser.class);//用户登陆过了传过去页面的信息
						}
					}
				}
			}
			return null;
		}
		/**
		 * 从cokkie中获取商品列表
		 * @param cookies
		 * @return
		 */
		private List<ShoppingPojo> getShoppingList(Cookie[] cookies){
			if(cookies!=null&&cookies.length>0){
				for(Cookie cookie:cookies){
					if(cookie.getName().equals("SHOPPING_LIST")){
						String shoppingList="";
						try {
							shoppingList = URLDecoder.decode(cookie.getValue(),"utf-8");
							if(shoppingList!=null&&shoppingList!=""){
								ObjectMapper objectMapper = new ObjectMapper();  
								JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, ShoppingPojo.class);  
								List<ShoppingPojo> list = objectMapper.readValue(shoppingList, javaType);
								return list;
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						}
					}
			}
			return null;
		}
}
